<template>
  <div class="details-page">
    <view class="header">
      <table class="details-page-table">
        <tr>
          <td class="label-td">是否计划</td>
          <td>{{ outboundData.holdType ? "库提" : "计划" }}</td>
          <td class="label-td">类型</td>
          <td>{{ OUTBOUND_TYPE[outboundData.outboundType] }}</td>
          <td class="label-td">状态</td>
          <td>{{ ORDER_TEXT[outboundData.status] }}</td>
        </tr>
        <tr>
          <td class="label-td">出库仓库</td>
          <td>
            {{ outboundData.warehouseCode }}-{{ outboundData.warehouseName }}
          </td>
          <td class="label-td">申请人</td>
          <td>{{ outboundData.creatorName }}</td>
          <td class="label-td">申请时间</td>
          <td>{{ timestampToDate(outboundData.createTime) }}</td>
        </tr>
        <tr>
          <td class="label-td">计划日期</td>
          <td>{{ timestampToDate(outboundData.scheduledFinishTime) }}</td>
          <td class="label-td">确认人</td>
          <td>{{ outboundData.receiverName }}</td>
          <td class="label-td">确认时间</td>
          <td>{{ timestampToDate(outboundData.receiveTime) }}</td>
        </tr>

        <tr>
          <td class="label-td">经手人</td>
          <td>{{ outboundData.processorName }}</td>
          <td class="label-td">备注</td>
          <td colspan="5">
            {{ outboundData.remark }}
          </td>
        </tr>
      </table>
    </view>

    <view class="content">
      <scroll-view scroll-y="true" class="scroll-view-style">
        <view
          v-for="(item, index) in outboundListData"
          :key="index"
          class="list-item"
        >
          <view class="list-item-line">
            <view class="list-item-line-text">
              <text>序号：</text> <text>{{ index + 1 }}</text></view
            >
            <view class="list-item-line-text">
              <text>出库数量：</text> <text>{{ item.quantity }}</text></view
            >
            <view class="list-item-line-text" v-if="receive">
              <text>已出库：</text>
              <text>{{ item.finishedQuantity }}</text></view
            >

            <view class="list-item-line-text">
              <!-- <text>物资类型：</text> -->
              <text
                class="status"
                :class="OUTBOUND_ORDER_STATUS[item.status]"
                v-if="!operation && !receive"
                >{{ OUTBOUND_ORDER_TEXT[item.status] }}</text
              >
              <text class="material">{{
                PRODUCT_TYPE[item.productType]
              }}</text></view
            >
          </view>
          <view class="list-item-line">
            <view class="list-item-line-text">
              <text>编号：</text> <text>{{ item.productCode }}</text></view
            >
          </view>
          <view class="list-item-line">
            <view class="list-item-line-text">
              <text>名称：</text> <text>{{ item.productName }}</text></view
            >
          </view>
          <view class="list-item-line">
            <view class="list-item-line-text batch">
              <text>批次：</text>
            </view>
            <view class="list-item-line-text left-auto">
              <text
                class="batch-item"
                v-for="b in outboundBatchData[item.id]"
                :key="b.id"
              >
                <text class="batch-text"> {{ b.batch || "---" }}</text>
                <uni-icons
                  v-if="
                    operation ||
                    (receive && item.quantity !== item.finishedQuantity)
                  "
                  @click="deleteBatchFn(b.id)"
                  type="closeempty"
                  size="14"
                  class="del-icon"
                ></uni-icons>
              </text>
            </view>
          </view>
          <view class="list-item-line">
            <view class="list-item-line-text">
              <text>备注：</text> <text>{{ item.remark || "---" }}</text></view
            >
          </view>

          <view
            class="list-item-line right"
            v-if="
              (operation || receive) && item.quantity !== item.finishedQuantity
            "
          >
            <view class="list-item-line-text">
              <text @click="batchAssignment(item.productId, item.id)"
                >分配批次</text
              >
              <text @click="toOutboundPage(item)" v-if="receive"
                >选择出库物资</text
              >
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    <view class="bottom-btn" v-if="operation">
      <!-- 接收确认 -- 取消和确认按钮 -->
      <view class="back-btn btn" @click="cancelPage">关闭</view>
      <view class="confirm-btn btn" @click="confirmPage">准备完成</view>
    </view>
    <view class="bottom-btn" v-if="receive">
      <!--接受-- 取消和确认按钮 -->
      <view class="back-btn btn" @click="cancelPage">关闭</view>
    </view>
    <!-- 分配批次 -->
    <uni-popup
      ref="popup"
      type="center"
      :is-mask-click="false"
      @maskClick="closeOperation"
      border-radius="10px 10px 0 0"
    >
      <view class="popup-content">
        <text class="popup-title">选择批次</text>
        <uni-table
          border
          stripe
          type="selection"
          emptyText="暂无数据"
          @selection-change="selectionBatchChange"
        >
          <!-- 表头行 -->
          <uni-tr>
            <uni-th width="50" align="center">序号</uni-th>
            <uni-th align="center">批次</uni-th>
            <uni-th align="left">数量</uni-th>
          </uni-tr>
          <!-- 表格数据行 -->
          <uni-tr v-for="(item, index) in batchList" :key="index">
            <uni-td align="center">{{ index + 1 }}</uni-td>
            <uni-td>{{ item.batch }}</uni-td>
            <uni-td>{{ item.quantity }}</uni-td>
          </uni-tr>
        </uni-table>
        <view class="split-btn">
          <!-- 取消和确认按钮 -->
          <view class="cancel-btn btn" @click="closeOperation">取消</view>
          <view class="confirm-btn btn" @click="confirmBatch">确认</view>
        </view>
      </view>
    </uni-popup>
  </div>
</template>

<script>
import {
  getOutboundDetails,
  getOutboundDetailsList,
  getBatchList,
  appendBatch,
  getBillBatch,
  deleteBatch,
  confirmCheckReady,
} from "@/service/outbound";
import { buildGetUrl, timestampToDate } from "@/common/utils";
import {
  STORAGE_KEY,
  OUTBOUND_ORDER_STATUS,
  RESPONSE_CODE,
  OUTBOUND_TYPE,
  PRODUCT_TYPE,
  ORDER_TEXT,
  OUTBOUND_ORDER_TEXT,
} from "@/common/constant";
export default {
  data() {
    return {
      OUTBOUND_ORDER_STATUS,
      PRODUCT_TYPE,
      ORDER_TEXT,
      OUTBOUND_ORDER_TEXT,
      OUTBOUND_TYPE,
      timestampToDate,
      queryId: "",
      outboundData: {},
      outboundListData: [],
      outboundBatchData: [],
      operation: false,
      receive: false,
      productId: "",
      batchList: [],
      confirmContainerList: [],
      selectedBatchIndexs: [], // 选中的批次索引
      outboundListId: "",
    };
  },
  onShow() {
    this.loadData();
  },
  onLoad(options) {
    this.queryId = options.id;
    if (options.mark === "operation") {
      this.operation = true;
    }
    if (options.mark === "receive") {
      //出库
      this.receive = true;
    }
  },
  methods: {
    // 跳转出库页面
    toOutboundPage(row) {
      const openData = {
        row: row,
        warehouseId: this.outboundData.warehouseId,
      };
      if (this.outboundData.holdType) {
        // 判断是否设置批次
        if (this.outboundBatchData[row.id]?.length > 0) {
          openData.batches = this.outboundBatchData[row.id].map(
            (item) => item.batch
          );
          openData.bindOrderFlag = false;
        } else {
          uni.showToast({
            title: "请分配批次",
            icon: "error",
          });
          return;
        }
      } else {
        openData.bindOrder = row.bindOrder;
        openData.bindOrderFlag = true;
      }
      let objStr = JSON.stringify(openData);
      uni.navigateTo({
        url: `/pages/taskPage/outbound/outboundPage?param=${encodeURIComponent(
          objStr
        )}`,
      });
    },

    closeOperation() {
      this.$refs.popup.close();
    },

    cancelPage() {
      uni.navigateBack({
        delta: 1,
      });
    },

    // 分配批次
    batchAssignment(productId, id) {
      this.productId = productId;
      this.outboundListId = id;
      const params = {
        productId,
        warehouseId: this.outboundData.warehouseId,
      };
      const query = buildGetUrl(params);
      getBatchList(query).then((res) => {
        if (res.code === RESPONSE_CODE.SUCCESS) {
          this.batchList = res.data;
        }
      });
      this.$refs.popup.open();
    },
    // 选中批次勾选时触发
    selectionBatchChange(e) {
      this.selectedBatchIndexs = e.detail.index;
    },
    // 点击确认时
    confirmBatch() {
      if (!this.selectedBatchIndexs.length) {
        this.$refs.popup.close();
        return;
      }
      let activelist = [];
      // 根据this.selectedBatchIndexs数组中的索引，从this.batchList中取出对应的batch属性值
      this.selectedBatchIndexs.forEach((index) => {
        activelist.push(this.batchList[index].batch);
      });
      const params = {
        id: this.outboundListId,
        list: activelist,
      };

      appendBatch(params).then((res) => {
        if (res.code === RESPONSE_CODE.SUCCESS) {
          uni.showToast({
            title: "选择成功",
            icon: "seccess",
          });
          this.getBatchList();
          this.$refs.popup.close();
        } else {
          uni.showToast({
            title: res.msg,
            icon: "error",
            style: {
              width: "80%", // 设置宽度，使其能够容纳更多文字
            },
          });
        }
      });
    },

    // 删除批次
    deleteBatchFn(id) {
      // 二次确认
      uni.showModal({
        title: "提示",
        content: "是否确认删除？",
        success: (res) => {
          if (res.confirm) {
            const params = {
              id,
            };
            const query = buildGetUrl(params);
            deleteBatch(query).then((res) => {
              if (res.code === RESPONSE_CODE.SUCCESS) {
                this.getBatchList();
              }
            });
          }
        },
      });
    },
    // 确认接受
    confirmPage() {
      // 二次确认
      uni.showModal({
        title: "提示",
        content: "是否确认准备完成?",
        success: (res) => {
          if (res.confirm) {
            const params = {
              id: this.queryId,
            };
            const query = buildGetUrl(params);
            confirmCheckReady(query).then((res) => {
              if (res.code === RESPONSE_CODE.SUCCESS) {
                uni.showToast({
                  title: "确认成功",
                  icon: "success",
                });
                // 返回上一页并刷新
                uni.navigateBack({
                  delta: 1,
                });
              } else {
                uni.showToast({
                  title: res.msg,
                  icon: "error",
                  style: {
                    width: "80%", // 设置宽度，使其能够容纳更多文字
                  },
                });
              }
            });
          } else if (res.cancel) {
            console.log("用户点击取消");
          }
        },
      });
    },

    // 加载基础信息
    async loadData() {
      const params = {
        id: this.queryId,
      };
      const query = buildGetUrl(params);
      const res = await getOutboundDetails(query);
      if (res.code === RESPONSE_CODE.SUCCESS) {
        let titleText = `出库详情`;
        if (this.operation) {
          titleText = `出库申请单`;
        }
        uni.setNavigationBarTitle({
          title: `${titleText}-${res.data.orderNumber}`,
        });
        this.outboundData = res.data;
      }
      this.getOutboundList();
      this.getBatchList();
    },
    // 加载列表信息
    async getOutboundList() {
      const params = {
        id: this.queryId,
      };
      const query = buildGetUrl(params);
      const listRes = await getOutboundDetailsList(query);
      if (listRes.code === RESPONSE_CODE.SUCCESS) {
        this.outboundListData = listRes.data;
      }
    },

    // 获取批次
    async getBatchList() {
      const params = {
        id: this.queryId,
      };
      const query = buildGetUrl(params);
      const batchRes = await getBillBatch(query);
      if (batchRes.code === RESPONSE_CODE.SUCCESS) {
        this.outboundBatchData = batchRes.data;
      }
    },
  },
};
</script>
<style lang="less" scoped>
.details-page {
  .header {
    background: #ecf5ff;
    padding: 10rpx;
    padding-bottom: 0rpx;
  }
  .details-page-table {
    width: 100%;
    // 边框合并
    border-collapse: collapse;
    font-size: 20rpx;
    color: #777;
    background: #fff;
    border-radius: 14rpx;
    tr,
    td {
      line-height: 40rpx;
      border: 1rpx solid #eee;
    }
    td:nth-child(odd) {
      text-align: center;
      background-color: #ebeef5;
    }
    td:nth-child(even) {
      padding-left: 10rpx;
    }
    .label-td {
      width: 100rpx;
    }
  }
  .scroll-view-style {
    height: 100%;
    padding: 10rpx;
    box-sizing: border-box;
  }
  .content {
    height: calc(100vh - 270rpx);
    background: #ecf5ff;

    .list-item {
      font-size: 12px;
      margin-bottom: 10rpx;
      background: #fff;
      border-radius: 14rpx;
      padding: 10rpx 20rpx;
      box-sizing: border-box;
      position: relative;
      .confirm-text {
        position: absolute;
        right: 20rpx;
        bottom: 10rpx;
        color: red;
        padding: 4rpx;
        font-size: 30rpx;
        text-align: center;
        border: 4rpx solid red;
        // 旋转
        transform: rotate(-30deg);
        .jieshou {
          font-size: 40rpx;
        }
      }
      .list-item-line {
        display: flex;
        justify-content: space-between;
        line-height: 50rpx;
        color: #777;

        .left-auto {
          flex: 1;
          display: flex;
          // 靠左对齐
          justify-content: flex-start;
          // 换行
          flex-wrap: wrap;
        }
        .batch-item {
          border: 1rpx solid #d9ecff;
          color: #409eff;
          background: #ecf5ff;
          padding: 0 20rpx;
          margin-right: 10rpx;
          display: flex;
          // 水平居中
          align-items: center;

          .del-icon {
            margin-left: 10rpx;
            color: red !important;
          }
        }
      }
      .right {
        justify-content: flex-end;
        text {
          margin-left: 40rpx;
          color: #409eff;
        }
      }
      .material {
        border: 1rpx solid #d9ecff;
        color: #409eff;
        background: #ecf5ff;
        padding: 0 10rpx;
        box-sizing: border-box;
        border-radius: 5rpx;
        font-size: 20rpx;
      }
    }
  }
  .bottom-btn {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 80rpx;
    overflow: hidden;
    display: flex;
    .btn {
      flex: 1;
      text-align: center;
      line-height: 80rpx;
      background: #f0f0f0;
    }
    .confirm-btn {
      color: #fff;
      background: #409eff;
    }
  }

  .popup-content {
    background: #fff;
    width: 500rpx;
    border-radius: 10rpx;
    padding: 10rpx 20rpx;
    .popup-title {
      font-size: 24rpx;
      line-height: 60rpx;
    }
    .uni-input {
      height: 60rpx;
      padding-left: 20rpx;
      font-size: 24rpx;
      border: 1rpx solid #eee;
    }
    .split-btn {
      margin-top: 20rpx;
      display: flex;
      justify-content: space-between;
      line-height: 80rpx;
      text-align: center;
      .btn {
        flex: 1;
        background: #f0f0f0;
        font-size: 24rpx;
      }
      .confirm-btn {
        color: #fff;
        background: #409eff;
      }
    }
  }
  .container-code {
    text-align: center;
    line-height: 70rpx;
  }

  .scroll-view-style-container {
    max-height: 600rpx;
  }

  .container-item {
    font-size: 12px;
    margin-bottom: 10rpx;
    background: #fff;
    border-radius: 14rpx;
    padding: 10rpx 20rpx;
    box-sizing: border-box;
    position: relative;

    .list-item-line {
      display: flex;
      justify-content: space-between;
      line-height: 50rpx;
      color: #777;
    }

    .material {
      border: 1rpx solid #d9ecff;
      color: #409eff;
      background: #ecf5ff;
      padding: 0 10rpx;
      box-sizing: border-box;
      border-radius: 5rpx;
      font-size: 20rpx;
    }
  }
  .container-btn {
    margin-top: 20rpx;
    display: flex;
    justify-content: space-between;
    line-height: 80rpx;
    text-align: center;
    .btn {
      flex: 1;
      background: #f0f0f0;
      font-size: 24rpx;
    }
    .confirm-btn {
      color: #fff;
      background: #409eff;
    }
  }
}
</style>
